/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.push.application.impl;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.bsl.push.application.CheckinEvent;
import com.foreveross.bsl.push.application.vo.DeviceCheckinVo;
import com.foreveross.bsl.push.domain.entity.Push;
import com.foreveross.bsl.push.repository.PushRepository;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

/**
 * 离线推送处理器
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-7-10
 *
 */
@Named
public class OfflinePushHandler {
	
	private final static Logger log = LoggerFactory.getLogger(OfflinePushHandler.class);

	@Inject
	private EventBus eventBus;
	
	@Inject
	private PushDispatcher pushDispatcher;
	
	@PostConstruct
	public void init(){
		eventBus.register(this);
		log.info("注册CheckinEvent事件监听器:{}", this);
	}
	
	/**
	 * 处理签到事件
	 * @param evt
	 */
	@Subscribe
	public void handleCheckinEvent(CheckinEvent evt){
		DsRouterHelper.setCurrentDsRouter(evt.getDsRouter());
		if(CheckinEvent.Action.Checkin.equals(evt.getAction())){
			this.handleOfflinePush(evt.getCheckinInfo());
		}
	}
	
	private final PushRepository getPushRepository(){
		return new Push().getEntityRepository(PushRepository.class);
	}
	
	protected void handleOfflinePush(DeviceCheckinVo checkinInfo){
		//根据应用ID和别名获取所有在有效期内的离线推送
		Push push=getPushRepository().findOfflinePush(checkinInfo.getAppId(), checkinInfo.getDeviceId());
		if(push!=null){
			push.getTarget().setToken(checkinInfo.getPushToken());
			log.debug("处理离线推送:{},应用:{},设备:{}", push.getId(), checkinInfo.getAppId(), checkinInfo.getDeviceId());
			pushDispatcher.dispatch(push);
		}
	}
	
}
